package com.lipaluma.csv.io;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.field.mapper.mapping.Column;
import com.lipaluma.field.mapper.mapping.MappingInfo;
import com.lipaluma.io.Row;

/**
 * Row from a Csv File used for writing
 * 
 * @author Mario
 */
public class CsvWriteRow implements Row {

	private Map<Integer, String> line;
	
	/**
	 * create a csv row for writing
	 */
	public CsvWriteRow() {
		line = new HashMap<Integer, String>();
	}
	/**
	 * create a csv row for writing
	 */
	CsvWriteRow(CsvWriteRow row) {
		this();
		line.putAll(row.line);
	}
	
	public String extractValueOnIndex(int index) {
		return line.get(index);
	}

	public int getColumnNumbers() {
		int max = 0;
		for(Integer value : line.keySet())
			if(value > max)
				max = value;
		return max+1;
	}

	@Override
	public String extractValue(MappingInfo info) {
		throw new CsvParserException("The class CsvWriteRow is not applicable for extract values on line");
	}

	@Override
	public void writeValue(Object value, MappingInfo info) {
		Column columnInfo = (Column) info;
		if(value == null)
			line.put(columnInfo.getColumnIndex(), "");
		else 
			line.put(columnInfo.getColumnIndex(), value.toString());
	}

	@Override
	public String[] toArray() {
		int max = 0;
		for(Integer index : line.keySet()){
			if(max < index)
				max = index;
		}
		String[] result = new String[max];
		for(Entry<Integer, String> entry : line.entrySet()){
			result[entry.getKey()] = entry.getValue();
		}
		return result;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		CsvWriteRow row = new CsvWriteRow();
		row.line.putAll(line);
		return row;
	}
}
